
#include "stm32lib/stm32f10x_rcc.h"
#include "stm32lib/stm32f10x_pwr.h"

#include "rtc.h"

void Rtc::init(void)
{
  resetAfterPowerdown();

  // Enable Backup and Power clocks
  RCC_APB1PeriphClockCmd(RCC_APB1Periph_BKP, ENABLE);
  RCC_APB1PeriphClockCmd(RCC_APB1Periph_PWR, ENABLE);

  // Enable access to RTC and Backup Registers
  PWR_BackupAccessCmd(ENABLE);
  
  // Wait for RTC to start
  RTC_WaitForSynchro();
  RTC_WaitForLastTask();
}

void Rtc::resetAfterPowerdown(void)
{
  // Enable Backup and Power clocks
  RCC_APB1PeriphClockCmd(RCC_APB1Periph_BKP, ENABLE);
  RCC_APB1PeriphClockCmd(RCC_APB1Periph_PWR, ENABLE);

  // Enable access to RTC and Backup Registers
  PWR_BackupAccessCmd(ENABLE);

  // Reset the backup domain, clear RTC
  RCC_BackupResetCmd(ENABLE);
  RCC_BackupResetCmd(DISABLE);

  // Select HSE as RCC clock source
  RCC_RTCCLKConfig(RCC_RTCCLKSource_HSE_Div128);
  RCC_RTCCLKCmd(ENABLE);

  // Wait for RTC to start
  RTC_WaitForSynchro();
  RTC_WaitForLastTask();

  // Set RTC prescaler
  RTC_EnterConfigMode();
  RTC_SetPrescaler(RTC_CLOCK - 1);
  RTC_ExitConfigMode();
  RTC_WaitForLastTask();

  
  /* Prescaler configuration */
  RCC_ClocksTypeDef clocks;
  RCC_GetClocksFreq(&clocks);
}

RtcTimestamp Rtc::now(void)
{
  return RtcTimestamp(RTC_GetCounter());
}

void Rtc::setTime(const RtcTimestamp &timestamp)
{
  RTC_WaitForLastTask();
  RTC_EnterConfigMode();
  RTC_SetCounter(timestamp.getRawtime());
  RTC_ExitConfigMode();
  RTC_WaitForLastTask();
}


